/**
 * Copyright (c) 2014-2017, huli.com
 * All rights reserved.
 */
package com.xiaohujr.xuexue.vm.gc;

import java.util.concurrent.TimeUnit;

/**
 * finalize是GC时可以拯救对象的地方,
 * 但是只会被调用一次.
 * <p>
 * 新生代回收算法:复制算法,新生代对象死得快(大批死去少量存活),将内存分为一个大的Eden空间和两块娇小的Survivor空间.HotSpot虚拟机默认比例是8:1.
 * 老年代回收算法:标记-整理(所有存活对象向内存一端移动,清除边界外内存),标记-清理(把标记的对象直接清除).
 *
 * @author Xue Xue (xuexue1@huli.com)
 * @version $Id$
 * @since 2018/5/3
 */
public class FinalizeEscapeGC {
    public static FinalizeEscapeGC SAVE_HOOK = null;

    public void isAlive() {
        System.out.println("i'm alive~!");
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("finalizing!");
        FinalizeEscapeGC.SAVE_HOOK = this;
    }

    public static void main(String[] args) throws InterruptedException {
        SAVE_HOOK = new FinalizeEscapeGC();

        SAVE_HOOK = null;
        System.gc();
        TimeUnit.SECONDS.sleep(1);
        if (SAVE_HOOK != null) {
            SAVE_HOOK.isAlive();
        } else {
            System.out.println("i'm dead!");
        }

        SAVE_HOOK = null;
        System.gc();
        TimeUnit.SECONDS.sleep(1);
        if (SAVE_HOOK != null) {
            SAVE_HOOK.isAlive();
        } else {
            System.out.println("i'm dead!");
        }
    }

}
